package net.atomarrow.aop;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

import net.atomarrow.db.tx.TransactionInterceptor;
import net.atomarrow.ioc.ApplicationContext;
import net.atomarrow.util.PriorityUtil;

/**
 * 拦截器控制器
 * 
 * @author Michael
 * 
 */
public class InterceptorKeeper {

    private List<ControllerInterceptor> controllerInterceptors;
    private List<ServiceInterceptor> serviceInterceptors;



    public InterceptorKeeper() {
        controllerInterceptors = new ArrayList<ControllerInterceptor>();
        serviceInterceptors = new ArrayList<ServiceInterceptor>();
        loadSysInterceptors();
    }

    private void loadSysInterceptors() {
        TransactionInterceptor txInterceptor = new TransactionInterceptor();
        ApplicationContext.load(txInterceptor);
        serviceInterceptors.add(txInterceptor);
    }

    public void loadInterceptors(List<String> paths) {
        Class clazz;
        try {
            for (String path : paths) {
                clazz = Class.forName(path);
                if(ControllerInterceptor.class.isAssignableFrom(clazz)){
                    controllerInterceptors.add((ControllerInterceptor) clazz.newInstance());
                }
                if(ServiceInterceptor.class.isAssignableFrom(clazz)){
                    serviceInterceptors.add((ServiceInterceptor) clazz.newInstance());
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        sortInterceptors();
    }

    private void sortInterceptors() {
    	this.controllerInterceptors = PriorityUtil.sort(controllerInterceptors);
    	this.serviceInterceptors=PriorityUtil.sort(serviceInterceptors);
    }
   

	public List<ControllerInterceptor> getControllerInterceptors() {
        return controllerInterceptors;
    }

    public void setControllerInterceptors(
            List<ControllerInterceptor> controllerInterceptors) {
        this.controllerInterceptors = controllerInterceptors;
    }

    public List<ServiceInterceptor> getServiceInterceptors() {
        return serviceInterceptors;
    }

    public void setServiceInterceptors(
            List<ServiceInterceptor> serviceInterceptors) {
        this.serviceInterceptors = serviceInterceptors;
    }

    public boolean hasServiceInterceptor() {
        return !serviceInterceptors.isEmpty();
    }

    public boolean hasControllerInterceptor() {
        return !controllerInterceptors.isEmpty();
    }

}
